# app.py
import os
from fastapi import FastAPI, File, UploadFile, HTTPException, Response,Form
from fastapi.responses import StreamingResponse
import shutil
app = FastAPI()

@app.post("/upload/")
async def upload_file(
        file: UploadFile = File(...),
        custom_param: str = Form(...)
):
    folder = "uploads/"
    file_content = await file.read()
    filename = os.path.join(folder, file.filename)
    os.makedirs(folder, exist_ok=True)

    with open(filename, "wb") as f:
        f.write(file_content)

    return {"filename": file.filename, "custom_param": custom_param, "message": "File uploaded successfully!"}

@app.get("/download/{filename}")
async def download_file(filename: str):
    folder = "uploads/"
    filepath = os.path.join(folder, filename)

    if not os.path.exists(filepath):
        raise HTTPException(status_code=404, detail="File not found")

    with open(filepath, "rb") as f:
        content = f.read()

    return Response(content=content, media_type="application/octet-stream")


@app.get("/download/stream/{filename}")
async def download_file_stream(filename: str):
    folder = "uploads/"
    filepath = os.path.join(folder, filename)

    if not os.path.exists(filepath):
        raise HTTPException(status_code=404, detail="File not found")

    return StreamingResponse(open(filepath, "rb"), media_type="application/octet-stream")


@app.get("/exists/{filename}")
async def file_exists(filename: str):
    folder = "uploads/"
    filepath = os.path.join(folder, filename)

    return {"exists": os.path.exists(filepath)}

@app.delete("/delete/{filename}")
async def delete_file(filename: str):
    folder = "uploads/"
    filepath = os.path.join(folder, filename)
    target_folder = 'deleted'
    if os.path.exists(filepath):
        os.makedirs(target_folder, exist_ok=True)
        target_filepath = os.path.join(target_folder, filename)
        shutil.move(filepath, target_filepath)
        return {"message": f"File {filename} deleted successfully."}
    else:
        raise HTTPException(status_code=404, detail="File not found")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)
